package org.ceva.training.controller;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.validation.BindException;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.ceva.training.util.upload.CommandClass;
import org.ceva.training.exception.BusinessException;



public class FileUploadController extends SimpleFormController {
	private final Log logger = LogFactory.getLog(getClass());
	private long maxFileSize;
	
	public FileUploadController(long maxFileSize) {
		super();
		this.maxFileSize = maxFileSize;
	}

	public final String getText(final String msgKey) {
		return getMessageSourceAccessor().getMessage(msgKey);
	}

	protected ModelAndView onSubmit(
        HttpServletRequest request,
        HttpServletResponse response,
        Object command,
        BindException errors) throws ServletException, IOException,Exception {
		
		ModelAndView mav = null;
		logger.info("Calling File Upload Controller");
		try
					{		//  MultiPart Request 
						CommandClass FileUploadCommandClass = (CommandClass) command;						
				        MultipartFile file = FileUploadCommandClass.getFile();	
						logger.info("File IS HERE "+file);
						if(file == null)
						{
							// file is null
						}else{
					        
					        logger.info("File Size : "+file.getSize());
					        long uploadedFileSize = file.getSize();
					        if(uploadedFileSize > this.maxFileSize){
					        	//fileSizeError
					        }
					        else
					        {
					        }
						}
						
							mav =  new ModelAndView("","ZycusSFC","");
						
					}	
					catch(BusinessException be)//Handle BusinessException Here
					{ 
						logger.info("BusinessException caught in Controller");
						request.setAttribute("warning",be.getMessage());
					}
					catch(MaxUploadSizeExceededException m){
						request.setAttribute("warning",getText("file.ClassNotFoundException"));
						logger.info("File Size Exceeds");
					}
					catch(Exception e)
					{
						logger.info("System Exception ");
						request.setAttribute("error",getText("error.unexpectedError"));
						e.printStackTrace();
					}	
					finally
					{
						if(mav == null)
							mav = new ModelAndView("blank");
						
					}
	      return mav;      
    }

}



